import axios from 'axios'

const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL, // api base_url
  timeout: 8000 // 请求超时时间
})
const getToken = () => {
  return service.post('/sys/loginjwt?password=123456&username=simpo').then((res: any) => {
    return res.result
  })
}
// 拦截器
service.interceptors.request.use(
  async (config) => {
    if (
      !config.url?.includes('/loginjwt') &&
      (config.url?.includes('/back') ||
        config.url?.includes('/upload') ||
        config.url?.includes('/sys'))
    ) {
      const token: any = await getToken()
      if (token) {
        // 将token添加到请求头中
        config.headers.Authorization = token
      }
    }
    return config
  },
  (err) => {
    Promise.reject(err)
  }
)

service.interceptors.response.use(
  (res) => {
    // 校验 token是否过期 或者 未登录
    return res.data
  },
  (err) => {
    Promise.reject(err)
  }
)

const serviceFile = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL, // api base_url
  timeout: 8000 // 请求超时时间
})
// 设置导出文件响应格式为二机制
serviceFile.interceptors.request.use(
  async (config) => {
    if (
      !config.url?.includes('/loginjwt') &&
      (config.url?.includes('/back') ||
        config.url?.includes('/upload') ||
        config.url?.includes('/sys'))
    ) {
      const token: any = await getToken()
      if (token) {
        // 将token添加到请求头中
        config.headers.Authorization = token
      }
    }
    config.responseType = 'blob'
    return config
  },
  (err) => {
    Promise.reject(err)
  }
)

const downFile = (data: any, fileName: string): any => {
  const objectUrl = URL.createObjectURL(data)
  // 文件地址
  const link = document.createElement('a')
  link.download = decodeURI(fileName) 
  link.href = objectUrl
  link.click()
  return { code: 10000, msg: '文件下载成功', result: '文件下载成功' }
}
// 读取服务端的文件
serviceFile.interceptors.response.use(
  (res) => {
    // 获取文件名
    const content = res.headers['content-disposition']
    const fileName = res.config.headers.fileName || (content && content.split('=')[1])
    return downFile(res.data, fileName)
  },
  (err) => {
    Promise.reject(err)
  }
)
export { service as axios,serviceFile as axiosFile}
